<?php
namespace App\Http\Controllers;

use App\Service\DataReturnService as DRS;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use App\Common\Base;
use App\Service\TicketService;
/**
 * 优惠券逻辑
 */
class TicketController extends Controller
{
   
    
    /**
     * 2018-06-26
     * czw
     * 优惠卷列表
     */
    public function list(Request $R)
    {
        $token = $R->get('token');
        $userInfo = Base::getUserByToken($token);
        if($userInfo['code'] != '666'){
            return $userInfo;
        }
        $user   = $userInfo['data'];
        $use_where = [
            'tickets.business_id'   => $user['business_id'],
            'tickets.state'         => 0,
            'ticket_user.user_id'   => $user['id'],
            'ticket_user.is_delete' => 0,
            'ticket_user.state' => 0,
        ];
        $use_where[]=['tickets.expire_date','>',date('Y-m-d H:i:s')];
        $use_list = TicketService::get_ticket_type($use_where);//未使用且为过期
        $unuse_where = [
            'tickets.business_id'   => $user['business_id'],
            'tickets.state'         => 0,
            'ticket_user.user_id'   => $user['id'],
            'ticket_user.is_delete' => 0,
            'ticket_user.state' => 1,
        ];
        $unuse_list = TicketService::get_ticket_type($unuse_where);//已使用
        $Expired_where = [
            'tickets.business_id'   => $user['business_id'],
            'tickets.state'         => 0,
            'ticket_user.user_id'   => $user['id'],
            'ticket_user.is_delete' => 0,
            'ticket_user.state' => 0,
        ];
        $Expired_where[]=['tickets.expire_date','<',date('Y-m-d H:i:s')];
        $Expired_list = TicketService::get_ticket_type($Expired_where);//已使用
        return DRS::returnOk(['use_list'=>$use_list,'unuse_list'=>$unuse_list,'Expired_list'=>$Expired_list],'获取优惠券列表成功');
    }
    
    public function detail(Request $request)
    {
        $business_id    = $request->get('business_id');
        $validator      = Validator::make(['business_id' => $business_id], 
                                    [
                                        'business_id'   => 'required|numeric',
                                    ]);

        if ($validator->fails()) {
            return DRS::returnError(1000,'验证错误！',$validator->errors());
        }

        $ticketQuerty = DB::table('tickets')->where(['business_id'=> $business_id, 'state' => 0])->first();
        if($ticketQuerty == null){
            return DRS::returnError(1000,'该优惠券不存在！');
        }else{
            return DRS::returnOk((array)$ticketQuerty);
        }
        
    }

    /**
     * 2018-06-22
     * czw
     * 领取优惠卷  绑定手机号才可以领
     * @params ticket_id
     * @return array
     */
    public function add(Request $R) 
    {
        $data = $R->post();
        $userInfo = Base::getUserByToken($data['token']);
        if($userInfo['code'] != '666'){
            return $userInfo;
        }
        $user   = $userInfo['data'];
        $validator = Validator::make($data,
                [
                    'ticket_id' => 'required|numeric',
                ],
                [
                    'ticket_id.required' => '优惠券id不能为空',
                    'ticket_id.numeric' => '优惠券id必须是数字',
                ]);
        if ($validator->fails()) {
            return DRS::returnError(20003,$validator->errors()->first());
        }
        $row_ticket = DB::table('tickets')->where(array('id'=>$data['ticket_id']))->first();
        if(!$row_ticket){
            return DRS::returnError(20005,'不存在该优惠券');
        }
        $ticket_user_insert = [
            'user_id'       => $user['id'],
            'ticket_id'     => $data['ticket_id'],
            'create_date'   => date('Y-m-d H:i:s'),
        ];
        
        $row = DB::table('ticket_user')->where(array('user_id'=>$user['id'],'ticket_id'=>$data['ticket_id'],'is_delete' => 0))->first();
        if($row){
            return DRS::returnError(20004,'您已经领取过优惠券了');
        }
        $row_ticket = DB::table('ticket_user')->insert($ticket_user_insert);
        if($row_ticket){
            return DRS::returnOk($row_ticket,'获取优惠券成功');
        }else{
            return DRS::returnError(20283,'获取优惠券失败');
        }
        
    }

    /**
     * @Notes:优惠卷弹窗自动领取
     * @param Request $request
     * @return array
     * @author: LiBaoJin
     * @Time:
     */
    public function coupon_custom_list(Request $request){
        $postData  = ['token' => $request->post('token'), 'business_id' => $request->post('business_id')];
        $validator = Validator::make($postData,
            [
                'token'         => 'required|string',
                'business_id'     => 'required',
            ]);

        if ($validator->fails()) {
            return DRS::returnError(1000,'验证错误！',$validator->errors());
        }
        $where = [
            'business_id'=> $postData['business_id'],
            'state'       =>0,
        ];
        $ticket = DB::table('tickets')->where($where)->get()->toArray();
        if(empty($ticket)){
            return DRS::returnOk([],'获取优惠券成功');
        }
        $ticket = array_map('get_object_vars', $ticket);

        foreach($ticket as $tik=>$tiv){
            if(!empty($tiv['get_start_time'])){
                unset($ticket[$tik]);continue;//如果存在领取时间的说明是手动领取优惠卷，干掉
            }
            if($tiv['expire_date']<date('Y-m-d')){
                unset($ticket[$tik]);continue; //如果使用结束时间小于当前时间的时候，说明优惠卷已经过期干掉
            }
        }
        $receive = '';
        if(empty($ticket)){
            $receive = 1;
            return DRS::returnOk(['receive'=>$receive,'ticket'=>'']);
        }
        $ticket_popup = DB::table('ticket_popup')->where(['business_id'=> $postData['business_id'], 'state' => 0])->first();
        if(empty($ticket_popup)){
            return DRS::returnOk([],'您还没有模板');
        }
        try{
            $userInfo = Base::getUserByToken($postData['token']);
            if($userInfo['code'] != '666'){
                return $userInfo;
            }
            $ticket_id = DB::table('ticket_user')->where(['user_id'=>$userInfo['data']['id'] , 'is_delete' => 0])->get()->toArray();
            $ticket_s = array_column($ticket,'id');
            if(!empty($ticket_id)){
                $ticket_id = array_map('get_object_vars', $ticket_id);
                $user_ticket = array_column($ticket_id,'ticket_id');
                foreach($ticket_s as $k=>$v){
                    if(in_array($v,$user_ticket)){
                        unset($ticket_s[$k]);
                    }
                }
                if(empty($ticket_s)){
                    $receive=1; //已领取
                }else{
                    $receive=2; //还有未领取
                    foreach($ticket_s as $k=>$v){
                        DB::table('ticket_user')->insert([
                            'user_id'       => $userInfo['data']['id'],
                            'ticket_id'     => $v,
                            'create_date'   => date('Y-m-d H:i:s'),
                        ]);
                    }
                }
                return DRS::returnOk(['receive'=>$receive,'ticket'=>$ticket_popup->picture]);
            }else{
                $receive=2; //完全没有领取优惠卷
                foreach($ticket_s as $k=>$v){
                    DB::table('ticket_user')->insert([
                        'user_id'       => $userInfo['data']['id'],
                        'ticket_id'     => $v,
                        'create_date'   => date('Y-m-d H:i:s'),
                    ]);
                }
                return DRS::returnOk(['receive'=>$receive,'ticket'=>$ticket_popup->picture]);
            }
        }catch(\Exception$e){
            return DRS::returnError(10003,'验证错误！',$e);
        }
    }
    public function get_coupon_by_id(Request$request){
        $postData  = ['token' => $request->post('token'), 'product_ids' => $request->post('product_ids')];
        $validator = Validator::make($postData,
            [
                'token'         => 'required|string',
                'product_ids'     => 'required|array',
            ]);

        if ($validator->fails()) {
            return DRS::returnError(1000,'验证错误！',$validator->errors());
        }
        $userInfo = Base::getUserByToken($postData['token']);
        if($userInfo['code'] != '666'){
            return $userInfo;
        }
        $user   = $userInfo['data'];
        $use_where = [
            'tickets.business_id'   => $user['business_id'],
            'tickets.state'         => 0,
            'ticket_user.user_id'   => $user['id'],
            'ticket_user.is_delete' => 0,
            'ticket_user.state' => 0,
        ];
        $use_where[]=['tickets.expire_date','>',date('Y-m-d H:i:s')];
        $use_list = TicketService::get_ticket_type($use_where);//未使用且为过期
        return $use_list;
    }

    /**
     * @Notes:返回可使用手动领取优惠卷
     * @param Request $request
     * @return array
     * @author: LiBaoJin
     * @Time:
     */
    public function get_coupon_add(Request$request){
        $postData  = ['token' => $request->post('token'), 'business_id' => $request->post('business_id')];
        $validator = Validator::make($postData,
            [
                'token'         => 'required|string',
                'business_id'     => 'required',
            ]);

        if ($validator->fails()) {
            return DRS::returnError(1000,'验证错误！',$validator->errors());
        }
        $userInfo = Base::getUserByToken($postData['token']);
        if($userInfo['code'] != '666'){
            return $userInfo;
        }
        $where = [
            'business_id'=> $postData['business_id'],
            'state'       =>0,
        ];
        $ticket = DB::table('tickets')->where($where)->get()->toArray();
        if(empty($ticket)){
            return DRS::returnOk([],'获取优惠券成功');
        }
        $ticket = array_map('get_object_vars', $ticket);
        foreach($ticket as $tik=>$tiv){
            if(empty($tiv['get_start_time'])){
                unset($ticket[$tik]);continue;//如果不存在领取时间的说明是自动领取优惠卷，干掉
            }
            if($tiv['get_start_time']>date('Y-m-d 0:0:0')){
                unset($ticket[$tik]);continue;//如果领取时间大于当前时间说明还没有开始领取，干掉
            }
            if($tiv['get_end_time']<date('Y-m-d 23:59:59')){
                unset($ticket[$tik]);continue;//如果领取结束时间小于当前时间说明已经结束，干掉
            }
        }
        $ticket = array_values($ticket);
        $ticket[0]['count']='';
        $ticket[0]['receive']=1;
        if(!empty($ticket)){
            $cound_id = array_column($ticket,'id');
            $users = DB::table('ticket_user')->where(['ticket_id'=>$cound_id[0]])->get()->toArray();
            $user_ids = array_map('get_object_vars', $users);
            $count = count($user_ids);
            $ticket[0]['count'] = $count;
            $is_head = DB::table('ticket_user')->where(['ticket_id'=>$cound_id[0],'user_id'=>$userInfo['data']['id']])->get()->toArray();
            if(!empty($is_head)){
                $ticket[0]['receive']=2;
            }

        }

        $ticket_popup = DB::table('ticket_popup')->where(['business_id'=> $postData['business_id'], 'state' => 0])->first();
        if(empty($ticket_popup)){
            return DRS::returnError([],'您还没有模板');
        }
        return DRS::returnOk($ticket);
    }

    /**
     * @Notes:手动领取优惠卷
     * @param Request $request
     * @return array
     * @author: LiBaoJin
     * @Time:
     */
    public function add_hand_coupon(Request$request){
        $postData  = ['token' => $request->post('token'), 'business_id' => $request->post('business_id'),'id'=>$request->post('id')];
        $validator = Validator::make($postData,
            [
                'token'         => 'required|string',
                'business_id'  => 'required',
                'id'            => 'required',
            ]);
        if ($validator->fails()) {
            return DRS::returnError(1000,'验证错误！',$validator->errors());
        }
        try{
            $userInfo = Base::getUserByToken($postData['token']);
            if($userInfo['code'] != '666'){
                return $userInfo;
            }
            $ticket_id = DB::table('ticket_user')->where(['user_id'=>$userInfo['data']['id'] , 'is_delete' => 0])->get()->toArray();
            $ticket_s = array_column($ticket_id,'ticket_id');
            if(in_array($postData['id'],$ticket_s)){
                $users = DB::table('ticket_user')->where(['ticket_id'=>$postData['id']])->get()->toArray();
                $user_ids = array_map('get_object_vars', $users);
                $count = count($user_ids);
                return DRS::returnOk(['count'=>$count],'您已领取该优惠卷');
            }
            DB::table('ticket_user')->insert([
                'user_id'       => $userInfo['data']['id'],
                'ticket_id'     => $postData['id'],
                'create_date'   => date('Y-m-d H:i:s'),
            ]);
            $users_count = DB::table('ticket_user')->where(['ticket_id'=>$postData['id']])->get()->toArray();
            $users_counts = array_map('get_object_vars', $users_count);
            $counts = count($users_counts);
            return DRS::returnOk(['count'=>$counts],'您已领取该优惠卷');
        }catch(\Exception$e){
            return DRS::returnError(10003,'验证错误！',$e);
        }
    }
}